package com.ebt.m.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.account.AccountHttps;
import com.ebt.m.commons.widgets.view.EBTDialog;
import com.ebt.m.config.BindType;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.ebt.m.commons.utils.NetUtils;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 用户绑定信息显示页面
 * 如果用户的 phone 不为空，则显示 phone；为空，则网络获取 UserInfo 中的 phone
 */
public class SettingActivity extends BaseToolBarActivity {

    @BindView(R.id.tv_phone_bind)
    TextView tv_phone_bind;
    @BindView(R.id.tv_wechat_bind)
    TextView tv_wechat_bind;
    @BindView(R.id.tv_qq_bind)
    TextView tv_qq_bind;
    @BindView(R.id.tv_sinaweibo_bind)
    TextView tv_sinaweibo_bind;

    @BindView(R.id.phone_container)
    RelativeLayout phone_container;
    @BindView(R.id.wechat_container)
    RelativeLayout wechat_container;
    @BindView(R.id.qq_container)
    RelativeLayout qq_container;
    @BindView(R.id.sina_weibo_container)
    RelativeLayout sina_weibo_container;
    @BindView(R.id.change_password_container)
    RelativeLayout change_password_container;
    @BindView(R.id.cancel_authentication_container)
    RelativeLayout cancel_authentication_container;

    ProgressDialog mProgressDialog;
    String mPhoneNumber;
    String mBindType;
    private ProgressDialog mLoginOutDialog;
    private EBTDialog mLoginOutConfirmDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_safety_menu);
        ButterKnife.bind(this);
        initProgressDialog();
        initView();
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getBindInfo();
    }

    private void getBindInfo() {

        mBindType = AppContext.getCurrentUser().getBindType();
        updateBindThirdPartViews();
        mPhoneNumber = AppContext.getCurrentUser().getPhone();
        if (TextUtils.isEmpty(mPhoneNumber)) {
            updatePhoneFromServer();//兼容原因如升级所致，没有重新登录获取userinfo中的phone
        } else {
            updateBindPhoneView();
        }
    }

    private void updatePhoneFromServer() {
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast("请连接网络后获取绑定手机号信息");
            return;
        }
        //user的id出错
        if (AppContext.getCurrentUser().getUserId() <= 0) {
            return;
        }
        showProgressDialog();

        AccountHttps.getInstance().getUserInfoByUserId("userId",
                String.valueOf(AppContext.getCurrentUser().getUserId()),
                getUserInfoSubscriber());
    }

    private Observer getUserInfoSubscriber() {
        return new Observer<BaseDataResult<UserInfo>>() {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                updatePhone(null);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<UserInfo> responseJson) {
                updatePhone(responseJson);
            }
        };
    }

    private void updatePhone(BaseDataResult<UserInfo> userInfo) {
        hideProgressDialog();
        if (userInfo != null && userInfo.getData() != null
                && !TextUtils.isEmpty(userInfo.getData().getPhone())) {
            mPhoneNumber = userInfo.getData().getPhone();
            //更新手机号
            AppContext.getCurrentUser().setPhone(mPhoneNumber);
            //存储到本地
            EBTUserInfoHelper.saveUserKEY(AppContext.getCurrentUser());
        } else {
            ToastUtil.showGetUserInfoFail(userInfo);
            return;
        }
        updateBindPhoneView();
    }

    public void initView() {
        setTitle("设置");
    }

    @OnClick(R.id.change_password_container)
    public void onChangePasswordClicked() {
        Intent intent = new Intent(this, ChangePasswordActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.phone_container)
    public void onPhoneContainerClicked() {
        if (TextUtils.isEmpty(mPhoneNumber)) {
            Intent intent = new Intent(this, BindPhoneActivity.class);
            intent.putExtra(BindPhoneActivity.MODE, BindPhoneActivity.MODE_BIND);
            intent.putExtra(BindPhoneActivity.FROM, SettingActivity.class.getCanonicalName());
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, PhoneBindInstructionActivity.class);
            intent.putExtra(PhoneBindInstructionActivity.PHONE_NUMBER, mPhoneNumber);
            startActivity(intent);
        }
    }

    @OnClick(R.id.loginout_container)
    public void onLoginoutClicked() {
        mLoginOutConfirmDialog = new EBTDialog();
        mLoginOutConfirmDialog.setMessage("确定要退出登录吗？");
        mLoginOutConfirmDialog.setRightButton("退出", v -> AppContext.loginOut(this));
        mLoginOutConfirmDialog.setLeftButton("取消", v -> mLoginOutConfirmDialog.dismiss());
        mLoginOutConfirmDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
    }

    @OnClick(R.id.cancel_authentication_container)
    public void onCancelAuthClicked() {
        Intent intent = new Intent(this, CancelAuthConfirmActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
        if (mLoginOutConfirmDialog != null) {
            mLoginOutConfirmDialog.dismiss();
            mLoginOutConfirmDialog = null;
        }
        if (mLoginOutDialog != null) {
            mLoginOutDialog.dismiss();
            mLoginOutDialog = null;
        }
    }

    private void updateBindThirdPartViews() {
        if (TextUtils.isEmpty(mBindType)) {
            wechat_container.setVisibility(View.GONE);
            qq_container.setVisibility(View.GONE);
            sina_weibo_container.setVisibility(View.GONE);
            return;
        }
        if (BindType.QQ.equalsIgnoreCase(mBindType)) {
            tv_qq_bind.setText("已绑定");
            wechat_container.setVisibility(View.GONE);
            sina_weibo_container.setVisibility(View.GONE);
        } else if (BindType.Wechat.equalsIgnoreCase(mBindType)) {
            tv_wechat_bind.setText("已绑定");
            qq_container.setVisibility(View.GONE);
            sina_weibo_container.setVisibility(View.GONE);
        } else if (BindType.Weibo.equalsIgnoreCase(mBindType)) {
            tv_sinaweibo_bind.setText("已绑定");
            wechat_container.setVisibility(View.GONE);
            qq_container.setVisibility(View.GONE);
        } else {
            wechat_container.setVisibility(View.GONE);
            qq_container.setVisibility(View.GONE);
            sina_weibo_container.setVisibility(View.GONE);
        }
    }

    private void updateBindPhoneView() {
        if (TextUtils.isEmpty(mPhoneNumber)) {
            tv_phone_bind.setText("未绑定");
        } else {
            tv_phone_bind.setText(mPhoneNumber);
        }
    }

    private void initProgressDialog() {
        mProgressDialog = new ProgressDialog(SettingActivity.this, R.style.LightDialog);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("正在查询绑定信息...");
        mLoginOutDialog = new ProgressDialog(SettingActivity.this, R.style.LightDialog);
        mLoginOutDialog.setIndeterminate(true);
        mLoginOutDialog.setMessage(getResources().getString(R.string.login_outing));
    }

    private void showProgressDialog() {
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
